//
//  BubbleViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/7/24.
//

import Foundation
import LeanCloud
class MyBubbleViewModel: BaseViewModel {
    @Published var items = [BubbleMallDataBean]()
    @Published var selectedIndex: Int = 0
    @Published var status = ""
    
    
    func getData(_ isRefresh: Bool = false) {
        requestList(isRefresh: isRefresh) {
            try check(userManager.isLogin(), "请先登录")
            let query = LCQuery(className: "BubbleMallData")
            query.whereKey("hide", .notEqualTo(true))
            query.whereKey("userId", .equalTo(userManager.getUserId()))
            let list =  try await LeancloudManager.instance.getList(query: query, modeType: BubbleMallDataBean.self)
            try check(!isRefresh || !list.isEmpty, "暂无数据")
            return list
        } suc: { diarys in
            self.status = ""
            self.items.append(contentsOf: diarys)
        } fail: {
            self.status = $0.message
        }
    }
    
    func doBubble(roleId: String, id: String, isComment: Bool) {
        request {
            if roleId == userManager.getUserId() {
                if isComment {
                    userManager.user?.extraConfig?.bubbleCommentId = id
                } else {
                    userManager.user?.extraConfig?.bubbleId = id
                }
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    if let user = userManager.user {
                        try await LeancloudManager.instance.save(todo: user)
                        userManager.update()
                    }
                }
            } else {
                let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: roleId)
                try check(aiRole != nil, "装扮失败")
                if (isComment) {
                    aiRole?.bubbleCommentId = id
                } else {
                    aiRole?.bubbleId = id
                }
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    _ = try await BackupsManager.shared.getDelegateConfig()?.addAiRole(bean: aiRole!, isAdd: false)
                }
            }
            return ""
        } suc: { _ in
            showToast("装扮成功")
            NotificationCenter.default.post(name: .updateBubble, object: true)
        } fail: {
            showToast($0.message)
        }
    }
    
}
